package cn.wjdiankong.levideo.activity;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.AnimationDrawable;
import android.media.AudioManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.PowerManager;
import android.text.TextUtils;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.TextView;
import cn.wjdiankong.ijkplayer.manager.PlayStateParams;
import cn.wjdiankong.ijkplayer.manager.PlayerView;
import cn.wjdiankong.ijkplayer.manager.PlayerView.VideoClickListener;
import cn.wjdiankong.ijkplayer.manager.VideoijkBean;
import cn.wjdiankong.levideo.R;
import cn.wjdiankong.levideo.activity.LevideoGestureListener.DirectionListener;
import cn.wjdiankong.levideo.data.LevideoData;
import cn.wjdiankong.levideo.database.LocalStorage;
import cn.wjdiankong.levideo.dialog.ConfirmDialog;
import cn.wjdiankong.levideo.dialog.DownloadVideoDialog;
import cn.wjdiankong.levideo.dialog.VideoPopupMenu;
import cn.wjdiankong.levideo.dialog.VideoPopupMenu.MenuClickItemListener;
import cn.wjdiankong.levideo.dialog.VideoSettingDialog;
import cn.wjdiankong.levideo.utils.Const;
import cn.wjdiankong.levideo.utils.ImageLoaderUtils;
import cn.wjdiankong.levideo.utils.Logger;
import cn.wjdiankong.levideo.utils.NetworkUtil;
import cn.wjdiankong.levideo.utils.PreferenceUtil;
import cn.wjdiankong.levideo.utils.UIUtil;
import cn.wjdiankong.levideo.utils.UmengReportUtils;
import cn.wjdiankong.levideo.utils.Utils;
import cn.wjdiankong.levideo.view.RotateImageView;
import tv.danmaku.ijk.media.player.IMediaPlayer;
import tv.danmaku.ijk.media.player.IMediaPlayer.OnInfoListener;

public class VideoPlayerActivity extends BaseActivity{

	private int videoType = -1;
	private String videoTypeStr = "";
	private PowerManager.WakeLock wakeLock;

	private View rootView;
	private PlayerView player;
	private View mMenuButton;
	private VideoPopupMenu mMenu;
	private boolean isLocal = false;
	private LevideoData videoData;
	
	private GestureDetector gestureDetector;
	private LevideoGestureListener gestrueListener;
	
	private List<VideoijkBean> playDataList = new ArrayList<VideoijkBean>();
	private List<LevideoData> videoDataList = new ArrayList<LevideoData>();
	private int curVideoPosition = 0;
	
	private ImageView guideImg;
	private View guideLayout;
	private AnimationDrawable guideAnim;
	
	public final static int CODE_START = 1024;
	public final static int CODE_RESULT = 1025;
	
	//视频详细信息内容
	private TextView playCountTxt, likeCountTxt;
	private ImageView userImg;
	private RotateImageView musicImg;
	private TextView userTxt, musicTxt, userSubTxt;
	private ImageView pauseImg;
	private View playCountView, likeCountView;
	private View videoInfoView;
	
	protected ImageLoader imageLoader = null;
	protected DisplayImageOptions userIconOptions;
	
	private final static String GUIDE_ANIM = "guide_anim";
	private boolean isGuideAnim;
	
	public static void startDefault(Context ctx, ArrayList<LevideoData> dataList, int position, int type, boolean isLocal){
		Intent intent = new Intent(ctx, VideoPlayerActivity.class);
		intent.putExtra("video_position", position);
		intent.putExtra("video_type", type);
		intent.putExtra("is_local_video", isLocal);
		intent.putParcelableArrayListExtra("video_data_list", dataList);
		ctx.startActivity(intent);
	}
	
	public static void startDefaultResult(Activity act, ArrayList<LevideoData> dataList, int position, int type, boolean isLocal){
		Intent intent = new Intent(act, VideoPlayerActivity.class);
		intent.putExtra("video_position", position);
		intent.putExtra("video_type", type);
		intent.putExtra("is_local_video", isLocal);
		intent.putParcelableArrayListExtra("video_data_list", dataList);
		act.startActivityForResult(intent, CODE_START);
	}

	@SuppressLint("InflateParams")
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		rootView = getLayoutInflater().inflate(R.layout.activity_videopalyer, null);
		setContentView(rootView);
		initView();
		initData();
		isGestureFinish = false;
	}

	protected void initView(){
		super.initView();
		mMenuButton = (ImageView) rootView.findViewById(R.id.app_video_menu);
		mMenuButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				mMenu.toggleMenu();
			}
		});
		
		userImg = (ImageView) findViewById(R.id.user_img);
		userTxt = (TextView) findViewById(R.id.user_name);
		userSubTxt = (TextView) findViewById(R.id.user_sub_txt);
		playCountTxt = (TextView) findViewById(R.id.play_count_txt);
		likeCountTxt = (TextView) findViewById(R.id.like_count_txt);
		playCountView = findViewById(R.id.play_count_layout);
		likeCountView = findViewById(R.id.like_count_layout);
		pauseImg = (ImageView) findViewById(R.id.pause_img);
		
		//抖音
		musicImg = (RotateImageView) findViewById(R.id.music_img);
		musicTxt = (TextView) findViewById(R.id.music_txt);
		
		videoInfoView = findViewById(R.id.layout_video_info);
		
		initMenu();
		initGuideAnim();
	}

	@SuppressWarnings("deprecation")
	protected void initData(){
		super.initData();
		
		curVideoPosition = getIntent().getIntExtra("video_position", 0);
		videoDataList = getIntent().getParcelableArrayListExtra("video_data_list");
		if(videoDataList == null || videoDataList.size() == 0){
			UIUtil.showShortHintToast(getApplicationContext(), "获取视频数据失败");
			return;
		}
		if(curVideoPosition >= videoDataList.size()){
			UIUtil.showShortHintToast(getApplicationContext(), "视频数据出现异常");
			return;
		}
		
		videoData = videoDataList.get(curVideoPosition);
		
		for(LevideoData data : videoDataList){
			VideoijkBean bean = new VideoijkBean();
			bean.title = data.title;
			bean.url = data.videoPlayUrl;
			playDataList.add(bean);
		}

		videoType = getIntent().getIntExtra("video_type", -1);
		isLocal = getIntent().getBooleanExtra("is_local_video", false);

		player = new PlayerView(this, rootView);
		//本地的视频，显示进度条，抖音，火山，快手视频非常短，所以底部的的进度条不存在，而秒拍，今日头条时间长需要保留
		if(isLocal){
			player = player.hideHideTopBar(false);
			videoInfoView.setVisibility(View.GONE);
		}else if(videoType == Const.VIDEO_TYPE_DOUYIN || videoType == Const.VIDEO_TYPE_HUOSHAN || videoType == Const.VIDEO_TYPE_KUAISHOU){
			player = player.hideBottonBar(true);
			videoInfoView.setVisibility(View.VISIBLE);
		}else{
			player = player.hideHideTopBar(false);
			videoInfoView.setVisibility(View.GONE);
		}
		
		player.setScaleType(PlayerView.SCALETYPE_FITXY);
		player.setTitle(videoData.title).forbidTouch(false)
		.hideCenterPlayer(true)
		.setPlaySource(playDataList, curVideoPosition);
		
		PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
		wakeLock = pm.newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK, "liveTAG");
		wakeLock.acquire();

		mMenu.setPlayLocalVideo(isLocal);
		
		//手势监听
		gestrueListener = new LevideoGestureListener();
		gestrueListener.setDirectionListener(new DirectionListener() {
			@Override
			public void top() {
				//播放上一个视频
				curVideoPosition ++;
				if(curVideoPosition >= playDataList.size()){
					curVideoPosition = playDataList.size()-1;
					UIUtil.showShortHintToast(getApplicationContext(), "已经到底部啦,返回主页加载更多数据");
					return;
				}
				if(curVideoPosition < 0){
					return;
				}
				player.switchStream(curVideoPosition);
				player.startPlay();
				videoData = videoDataList.get(curVideoPosition);
				setVideoInfo();
				HashMap<String, String> params = new HashMap<String, String>();
				params.put("video_source", videoTypeStr);
				params.put("is_local", isLocal ? "yes" : "no");
				UmengReportUtils.report(UmengReportUtils.VIDEOPLAYER_SLIDE_UP, params);
			}
			
			@Override
			public void right() {
				finish();
				HashMap<String, String> params = new HashMap<String, String>();
				params.put("video_source", videoTypeStr);
				params.put("is_local", isLocal ? "yes" : "no");
				UmengReportUtils.report(UmengReportUtils.VIDEOPLAYER_RETURN, params);
			}
			
			@Override
			public void left() {
			}
			
			@Override
			public void bottom() {
				//播放下一个视频
				curVideoPosition --;
				if(curVideoPosition < 0){
					curVideoPosition = 0;
					UIUtil.showShortHintToast(getApplicationContext(), "已经到顶部啦,可以尝试往下滑动");
					return;
				}
				if(curVideoPosition >= videoDataList.size()){
					return;
				}
				player.switchStream(curVideoPosition);
				player.startPlay();
				videoData = videoDataList.get(curVideoPosition);
				setVideoInfo();
				HashMap<String, String> params = new HashMap<String, String>();
				params.put("video_source", videoTypeStr);
				params.put("is_local", isLocal ? "yes" : "no");
				UmengReportUtils.report(UmengReportUtils.VIDEOPLAYER_SLIDE_DOWN, params);
			}

			@Override
			public void click() {
				Logger.log("click video");
				player.toggleBarView();
				HashMap<String, String> params = new HashMap<String, String>();
				params.put("video_source", videoTypeStr);
				params.put("is_local", isLocal ? "yes" : "no");
				UmengReportUtils.report(UmengReportUtils.VIDEOPLAYER_CLICK, params);
			}
		});
		gestureDetector = new GestureDetector(this, gestrueListener);
		
		
		//秒拍，头条视频不循环播放，其他类型都循环播放
		if(videoType == Const.VIDEO_TYPE_TOUTIAO|| videoType == Const.VIDEO_TYPE_MIAOPAI){
			player.setCyclePlay(false);
		}else{
			player.setCyclePlay(true);
		}
		player.setOnInfoListener(new OnInfoListener() {
			@Override
			public boolean onInfo(IMediaPlayer mp, int newStatus, int extra) {
				Logger.log("play status:"+newStatus);
				if(newStatus == PlayStateParams.STATE_COMPLETED){
					HashMap<String, String> params = new HashMap<String, String>();
					params.put("video_source", videoTypeStr);
					params.put("is_local", isLocal ? "yes" : "no");
					UmengReportUtils.report(UmengReportUtils.VIDEOPLAYER_FINISH, params);
				}else if(newStatus == PlayStateParams.MEDIA_INFO_VIDEO_RENDERING_START){
					//可能需要一个延迟，避免loading失败
					rootView.postDelayed(new Runnable() {
						@Override
						public void run() {
							startGuideAnim();
						}
					}, 1000);
				}else if(newStatus == PlayStateParams.MEDIA_INFO_VIDEO_INTERRUPT){
					HashMap<String, String> params = new HashMap<String, String>();
					params.put("video_source", videoTypeStr);
					params.put("is_local", isLocal ? "yes" : "no");
					UmengReportUtils.report(UmengReportUtils.VIDEOPLAYER_ERROR, params);
				}
				return false;
			}
		});
		
		
		player.setVideoClickListener(new VideoClickListener(){
			@Override
			public void click(int type) {
				HashMap<String, String> params = new HashMap<String, String>();
				params.put("video_source", videoTypeStr);
				params.put("is_local", isLocal ? "yes" : "no");
				if(type == VideoClickListener.CLICK_PLAY){
					UmengReportUtils.report(UmengReportUtils.VIDEOPLAYER_PLAY, params);
				}else if(type == VideoClickListener.CLICK_PAUSE){
					UmengReportUtils.report(UmengReportUtils.VIDEOPLAYER_PASUE, params);
				}else if(type == VideoClickListener.CLICK_MENU){
					UmengReportUtils.report(UmengReportUtils.VIDEOPLAYER_MENU, params);
				}else if(type == VideoClickListener.CLICK_FINISH){
					UmengReportUtils.report(UmengReportUtils.VIDEOPLAYER_FINISH, params);
				}else if(type == VideoClickListener.CLICK_REPLAY){
					UmengReportUtils.report(UmengReportUtils.VIDEOPLAYER_REPLAY, params);
				}else if(type == VideoClickListener.SLIDE_PROGRESSBAR){
					UmengReportUtils.report(UmengReportUtils.VIDEOPLAYER_SLIDE_BAR, params);
				}
			}
		});
		
		videoTypeStr = Utils.getVideoTypeStr(videoType);
		HashMap<String, String> params = new HashMap<String, String>();
		params.put("video_source", videoTypeStr);
		params.put("is_local", isLocal ? "yes" : "no");
		UmengReportUtils.report(UmengReportUtils.VIDEOPLAYER_PLAY, params);
		
		//初始化视频信息
		imageLoader = ImageLoaderUtils.getInstance(getApplicationContext()).getImageLoader();
		userIconOptions = new DisplayImageOptions.Builder()
				.cacheInMemory(true)
				.cacheOnDisc(true)
				.showImageOnFail(R.drawable.user_icon_zhanwei)
				.build();
		setVideoInfo();
		if(pauseImg != null){
			pauseImg.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					if (player.isPlaying()) {
						pauseImg.setImageResource(R.drawable.detail_icon_play_normal);
						player.pausePlay();
					} else {
						pauseImg.setImageResource(R.drawable.detail_icon_pause_normal);
						player.startPlay();
					}
				}
			});
		}
		if(!isLocal && !NetworkUtil.isWifiNetworkAvailable(getApplicationContext())){
			final ConfirmDialog dialog = new ConfirmDialog(this);
			dialog.setContentTxt("您正在使用移动网络播放视频，可能产生较高流量费用");
			dialog.setLeftTxt("继续观看", new OnClickListener() {
				@Override
				public void onClick(View v) {
					player.startPlay();
					dialog.dimiss();
				}
			}).setRightTxt("取消", new OnClickListener() {
				@Override
				public void onClick(View v) {
					finish();
					dialog.dimiss();
				}
			}).show();
			return;
		}
		player.startPlay();
		
	}

	@SuppressLint("InflateParams")
	private void initMenu() {
		mMenu = new VideoPopupMenu(this);
		mMenu.setMenuShowAnchorView(mMenuButton);
		mMenu.setMenuClickItemListener(new MenuClickItemListener() {
			@Override
			public void clickItem(int type) {
				HashMap<String, String> params = new HashMap<String, String>();
				switch(type){
				case MenuClickItemListener.DOWNLOAD_VIDEO:
					downloadVideo();
					params.put("video_source", videoTypeStr);
					params.put("is_local", isLocal ? "yes" : "no");
					UmengReportUtils.report(UmengReportUtils.VIDEOPLAYER_DOWNLOAD, params);
					break;
				case MenuClickItemListener.COPY_VIDEO:
					Utils.copyContent(getApplicationContext(), videoData.videoDownloadUrl);
					UIUtil.showShortHintToast(getApplicationContext(), "复制成功");
					params.put("video_source", videoTypeStr);
					params.put("is_local", isLocal ? "yes" : "no");
					UmengReportUtils.report(UmengReportUtils.VIDEOPLAYER_COPY, params);
					break;
				case MenuClickItemListener.SETTING_VIDEO:
					showVideoSettingDialog();
					params.put("video_source", videoTypeStr);
					params.put("is_local", isLocal ? "yes" : "no");
					UmengReportUtils.report(UmengReportUtils.VIDEOPLAYER_SETTING, params);
					break;
				case MenuClickItemListener.DELETE_VIDEO:
					params.put("video_source", videoTypeStr);
					params.put("is_local", isLocal ? "yes" : "no");
					UmengReportUtils.report(UmengReportUtils.VIDEOPLAYER_DELETE, params);
					
					String path = videoDataList.get(curVideoPosition).videoPlayUrl;
					Uri uri = Uri.parse(path);
					path = uri.getPath();
					boolean isSucc = LocalStorage.getInstance().deleteLevideoData(path);
					if(isSucc){
						File file = new File(path);
						if(file.exists()){
							isSucc = file.delete();
							if(isSucc){
								Intent data = new Intent();
								data.putExtra("del_position", curVideoPosition);
								data.putExtra("del_type", videoType);
								setResult(CODE_RESULT, data);
								finish();
							}else{
								UIUtil.showShortHintToast(getApplicationContext(), "删除失败,请稍后重试");
							}
						}else{
							UIUtil.showShortHintToast(getApplicationContext(), "删除失败,请稍后重试");
						}
					}else{
						UIUtil.showShortHintToast(getApplicationContext(), "删除失败,请稍后重试");
					}
					break;
				}
			}
		});
	}
	
	private void initGuideAnim(){
		isGuideAnim = (boolean)PreferenceUtil.getValue(GUIDE_ANIM, false);
		guideImg = (ImageView)rootView.findViewById(R.id.guide_img);
		guideLayout = rootView.findViewById(R.id.guide_layout);
		guideImg.setBackgroundResource(R.drawable.guide_anim);
		guideAnim = (AnimationDrawable) guideImg.getBackground();
		guideLayout.setVisibility(View.GONE);
	}
	
	private void startGuideAnim(){
		if(guideAnim != null && !guideAnim.isRunning() && !isGuideAnim){
			guideLayout.setVisibility(View.VISIBLE);
			guideAnim.start();
			guideImg.postDelayed(new Runnable() {
				@Override
				public void run() {
					if(guideAnim.isRunning())
						guideAnim.stop();
					guideLayout.setVisibility(View.GONE);
					isGuideAnim = true;
					PreferenceUtil.setValue(GUIDE_ANIM, true);
				}
			}, 5000);
		}
	}
	
	private void setVideoInfo(){
		if(userImg != null && !TextUtils.isEmpty(videoData.authorImgUrl)){
			imageLoader.displayImage(videoData.authorImgUrl, userImg, userIconOptions);
		}
		if(playCountView != null){
			if(!TextUtils.isEmpty(videoData.formatPlayCountStr)){
				playCountTxt.setText(videoData.formatPlayCountStr+" 人观看");
				playCountView.setVisibility(View.VISIBLE);
			}else{
				playCountView.setVisibility(View.GONE);
			}
		}
		if(likeCountView != null){
			if(!TextUtils.isEmpty(videoData.formatLikeCountStr)){
				likeCountTxt.setText(videoData.formatLikeCountStr+" 人点赞");
				likeCountView.setVisibility(View.VISIBLE);
			}else{
				likeCountView.setVisibility(View.GONE);
			}
		}
		if(userTxt != null){
			userTxt.setText(videoData.filterUserNameStr);
		}else{
			userTxt.setText("昵称加载中...");
		}
		
		/**
		 * 如果用户有签名信息，就直接展示签名信息，比如抖音
		 * 如果用户没有签名信息，就把用户的位置+年龄
		 * 如果位置和年龄都没有，就暂时创建日期
		 */
		if(userSubTxt != null){
			userSubTxt.setVisibility(View.VISIBLE);
			String userSubStr = "";
			if(!TextUtils.isEmpty(videoData.authorSignature)){
				userSubStr = videoData.authorSignature;
			}else if(!TextUtils.isEmpty(videoData.authorAge)){
				userSubStr = videoData.authorAge;
			}else if(!TextUtils.isEmpty(videoData.authorCity)){
				userSubStr = userSubStr + " "+videoData.authorCity;
			}else if(!TextUtils.isEmpty(videoData.formatTimeStr)){
				userSubStr = "发布于: " + videoData.formatTimeStr;
			}else{
				userSubTxt.setVisibility(View.GONE);
			}
			userSubTxt.setText(userSubStr);
		}
		if(musicTxt != null){
			if(TextUtils.isEmpty(videoData.filterMusicNameStr)){
				musicTxt.setText("#视频原声#");
			}else{
				musicTxt.setText(videoData.filterMusicNameStr);
			}
		}
		if(musicImg != null && !TextUtils.isEmpty(videoData.musicImgUrl)){
			imageLoader.displayImage(videoData.musicImgUrl, musicImg, userIconOptions);
			musicImg.stopRotate();
			musicImg.startRotate();
		}
	}

	@SuppressLint({ "InflateParams", "InlinedApi" })
	private void downloadVideo(){
		DownloadVideoDialog dialog = new DownloadVideoDialog(this);
		dialog.setDownloadUrl(videoData.videoDownloadUrl)
		.setVideoUrl(videoData.videoPlayUrl).setVideoData(videoData)
		.setVideoType(videoType).show();
	}

	@SuppressLint("InflateParams")
	private void showVideoSettingDialog(){
		VideoSettingDialog dialog = new VideoSettingDialog(this);
		dialog.show();
	}

	@Override
	protected void onPause() {
		super.onPause();
		if (player != null) {
			player.onPause();
		}
		muteAudioFocus(getApplicationContext(), true);
	}

	@Override
	protected void onResume() {
		super.onResume();
		if (player != null) {
			player.onResume();
		}
		muteAudioFocus(getApplicationContext(), false);
		if (wakeLock != null) {
			wakeLock.acquire();
		}
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		if (player != null) {
			player.onDestroy();
		}
	}

	@Override
	public void onBackPressed() {
		if (player != null && player.onBackPressed()) {
			return;
		}
		super.onBackPressed();
		if (wakeLock != null) {
			wakeLock.release();
		}
	}

	/**
	 * @param bMute 值为true时为关闭背景音乐。
	 */
	public static boolean muteAudioFocus(Context context, boolean bMute) {
		boolean bool = false;
		AudioManager am = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
		if (bMute) {
			int result = am.requestAudioFocus(null, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN_TRANSIENT);
			bool = result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED;
		} else {
			int result = am.abandonAudioFocus(null);
			bool = result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED;
		}
		return bool;
	}

	/** 
	 * 将MotionEvent事件处理交给gestureDetector对象 
	 */  
	@Override  
	public boolean onTouchEvent(MotionEvent event) {
		return gestureDetector.onTouchEvent(event);
	} 
	
	@Override
	protected String getPageName() {
		return "video_player";
	}
	
}

